package priv.dajie.tzzq.main;

import priv.dajie.tzzq.bot.buff.BuffUser;
import priv.dajie.tzzq.bot.steam.exception.SteamLoginException;
import priv.dajie.tzzq.mail.Mail163;
import priv.dajie.tzzq.spider.dota.buff.BuffDotaSpider;
import priv.dajie.tzzq.spider.dota.buff.BuffInfos;
import priv.dajie.tzzq.spider.dota.c5.C5DotaSpider;
import priv.dajie.tzzq.spider.dota.c5.C5Infos;
import priv.dajie.tzzq.spider.model.SpiderInfo;
import priv.dajie.tzzq.spider.model.SpiderMode;
import priv.dajie.tzzq.common.DruidUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

public class SpiderMain {

    private static int c5ThreadNum;
    private static int buffThreadNum;
    private static BuffDotaSpider[] buffSpiders;
    private static C5DotaSpider[] c5Spiders;
    private static Thread[] buffSpiderThreads;
    private static Thread[] c5SpiderThreads;
    private static int runtime;
    private static BuffUser buffUser;

    static {
        System.out.println("开始初始化..");
        loadProperties();
        System.out.println("获取配置文件..");
        buffSpiders = new BuffDotaSpider[buffThreadNum];
        c5Spiders = new C5DotaSpider[c5ThreadNum];
        buffSpiderThreads = new Thread[buffThreadNum];
        c5SpiderThreads = new Thread[c5ThreadNum];
        buffUser = new BuffUser("dajiebot", "6988324HAIjie24");
        System.out.println("登录BUFF..");
        try {
            buffUser.login();
            System.out.println("buff登陆状态："+buffUser.isLogin());
        } catch (SteamLoginException e) {
            System.out.println("请输入验证码->");
            Scanner sc = new Scanner(System.in);
            while (true) {
                try {
                    buffUser.login(sc.nextLine());
                    break;
                } catch (SteamLoginException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }
        System.out.println("初始化完毕..");
    }

    public static void loadProperties() {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(System.getProperty("user.dir") + "/config/run.properties");
            properties.load(inputStream);
            c5ThreadNum = Integer.parseInt(properties.getProperty("c5-spider-num"));
            buffThreadNum = Integer.parseInt(properties.getProperty("buff-spider-num"));
            String[] runtimeStrs = properties.getProperty("run-time").split(":");
            runtime = Integer.parseInt(runtimeStrs[0]) * 3600 + Integer.parseInt(runtimeStrs[1]) * 60;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static int getCount(String table) {
        String sql = "SELECT COUNT(*) FROM ";
        Connection conn = DruidUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql + table);
            rs = ps.executeQuery();
            int count = 0;
            if (rs.next())
                count = rs.getInt(1);
            rs.close();
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtils.close(conn, ps, rs);
        }
        return 0;
    }

    private static DBCount dbmaxCount() {
        String tables[] = {"c5_selling", "c5_buying", "buff_selling", "buff_buying"};
        int counts[] = new int[4];
        for (int i = 0; i < 4; i++) {
            counts[i] = getCount(tables[i]);
        }
        return new DBCount(counts[0], counts[1], counts[2], counts[3]);
    }

    public static void main(String[] args) throws InterruptedException {
        long temp, time;
        SpiderInfo c5Info;
        SpiderInfo buffInfo;
        Mail163 mail163 = new Mail163();
        while (true) {
            try {
                time = ((System.currentTimeMillis() / 1000)) % (60 * 60 * 24) + 3600 * 8;
                temp = (time - runtime);
//                System.out.println(runtime);
//                System.out.println(time);
                if (true) {
                    DBCount dbCount = dbmaxCount();
                    mail163.send("TZZQ_SPIDER 开始执行", "c5_selling：" + dbCount.c5Selling + "\nc5_buying：" + dbCount.c5Buying + "\nbuff_selling：" + dbCount.buffSelling + "\nbuff_buying：" + dbCount.buffBuying);
                    c5Info = C5Infos.getC5Info(); // 获取c5信息
                    buffInfo = BuffInfos.getBuffInfo(); // 获取buff信息
                    for (int i = 0; i < c5ThreadNum; i++) { // 激活c5线程
                        c5Spiders[i] = new C5DotaSpider(SpiderMode.OLDTABLE);
                        c5SpiderThreads[i] = new Thread(c5Spiders[i]);
                        c5Spiders[i].setSpiderInfo(c5Info);
                        c5SpiderThreads[i].start();
                    }
                    for (int i = 0; i < c5ThreadNum; i++) { // 防止过早激活buff线程
                        c5SpiderThreads[i].join();
                    }
                    for (int i = 0; i < buffThreadNum; i++) { // 激活buff线程
                        buffSpiders[i] = new BuffDotaSpider(buffUser, SpiderMode.OLDTABLE);
                        buffSpiderThreads[i] = new Thread(buffSpiders[i]);
                        buffSpiders[i].setSpiderInfo(buffInfo);
                        buffSpiderThreads[i].start();
                    }
                    for (int i = 0; i < buffThreadNum; i++) { // 激活buff线程
                        buffSpiderThreads[i].join();
                    }
                    Thread.sleep(100000);
                    dbCount = dbmaxCount();
                    mail163.send("TZZQ_SPIDER 执行完毕", "c5_selling：" + dbCount.c5Selling + "\nc5_buying：" + dbCount.c5Buying + "\nbuff_selling：" + dbCount.buffSelling + "\nbuff_buying：" + dbCount.buffBuying);
                } else {
                    System.out.println("尚未到执行时间");
                    Thread.sleep(20000); // 20秒检测一次
                }
            } catch (Exception e) {
                e.printStackTrace();
                mail163.send("TZZQ_SPIDER 出错！！", "卧槽，出错了：\n" + e);
            }

        }
    }

    private static class DBCount {
        private int c5Selling;
        private int c5Buying;
        private int buffSelling;
        private int buffBuying;

        public DBCount(int c5Selling, int c5Buying, int buffSelling, int buffBuying) {
            this.c5Selling = c5Selling;
            this.c5Buying = c5Buying;
            this.buffSelling = buffSelling;
            this.buffBuying = buffBuying;
        }

        public int getC5Selling() {
            return c5Selling;
        }

        public int getC5Buying() {
            return c5Buying;
        }

        public int getBuffSelling() {
            return buffSelling;
        }

        public int getBuffBuying() {
            return buffBuying;
        }

        @Override
        public String toString() {
            return "DBCount{" +
                    "c5Selling=" + c5Selling +
                    ", c5Buying=" + c5Buying +
                    ", buffSelling=" + buffSelling +
                    ", buffBuying=" + buffBuying +
                    '}';
        }
    }
}
